#include "widget.h"
#include "qmimedatabase.h"
#include "ui_widget.h"
#include <QMediaPlaylist>
#include <QMenu>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
    ,notMove(false)
    ,durationSet(false)
    ,color(false)
{
    ui->setupUi(this);

    initUi();
    initPlay();
    initConnect();

    initDB();

    initData();
    initMusicList();

    //状态栏图标
    setWindowIcon(QIcon(":/pic/logo.png"));
    //添加到系统托盘
    TrayIcon = new QSystemTrayIcon(this);
    TrayIcon->setIcon(QIcon(":/pic/logo.png"));
    TrayIcon->setToolTip("音乐播放器");
    // TrayIcon->show();
    // 检查系统是否支持托盘
    if (!QSystemTrayIcon::isSystemTrayAvailable()) {
        qDebug() << "系统不支持托盘图标功能";
        QMessageBox::warning(this, "提示", "系统不支持托盘图标，无法使用该功能");
    } else {
        TrayIcon->show(); // 显示托盘图标
    }

    //托盘显示与退出
    QMenu* menu = new QMenu(this);
    menu->addAction("显示",this,&QWidget::showNormal);
    menu->addAction("退出",this,&Widget::onRbtnClicked);
    TrayIcon->setContextMenu(menu);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::initUi()
{
    this->setWindowFlag(Qt::FramelessWindowHint);
    setupShadow();

    //leftForm
    ui->widget_4->setIconAndText("推荐",(":/pic/recommend.png"),0);
    ui->widget_5->setIconAndText("听书",(":/pic/book.png"),1);
    ui->widget_6->setIconAndText("直播",(":/pic/live.png"),2);
    ui->widget_7->setIconAndText("我的喜欢",(":/pic/likes.png"),3);
    ui->widget_8->setIconAndText("本地下载",(":/pic/loads.png"),4);
    ui->widget_18->setIconAndText("最近播放",(":/pic/recent.png"),5);

    curPage = ui->page_5;
    ui->widget_5->showAnimation(true);

    ui->widget_2->showRandomRow(setRecImgAndText(),1);
    ui->widget_3->showRandomRow(setRecImgAndText(),2);

    ui->page_4->setPageText("我的喜欢");
    ui->page_5->setPageText("本地下载");
    ui->page_6->setPageText("最近播放");

    volume = new volumeForm(this);
    ui->volume->setStyleSheet("border-image:url(:/pic/volume.png);");
    ui->stackedWidget->setCurrentIndex(0);
    //创建歌词页面
    lrc = new lrcForm(this);
    lrc->setGeometry(11, 0 , ui->widget->width(), ui->widget->height());
    lrc->hide();

    ui->start->setStyleSheet("border-image:url(:/pic/stop.png);");

    ui->mode->setStyleSheet("border-image:url(:/pic/order.png);");

    ui->pic->setStyleSheet("border-image:url(:/pic/05.png);");
}

void Widget::initConnect()
{
    //控制窗口
    connect(ui->min, &QPushButton::clicked, this, &Widget::onMinClicked);
    connect(ui->max, &QPushButton::clicked, this, &Widget::onMaxClicked);

    connect(ui->widget_4,&leftForm::pageChange,this,&Widget::rightPageChange);
    connect(ui->widget_5,&leftForm::pageChange,this,&Widget::rightPageChange);
    connect(ui->widget_6,&leftForm::pageChange,this,&Widget::rightPageChange);
    connect(ui->widget_7,&leftForm::pageChange,this,&Widget::rightPageChange);
    connect(ui->widget_8,&leftForm::pageChange,this,&Widget::rightPageChange);
    connect(ui->widget_18,&leftForm::pageChange,this,&Widget::rightPageChange);

    connect(ui->page_4,&rightForm::upDatePage,this,&Widget::upDatePageOfLike);
    connect(ui->page_5,&rightForm::upDatePage,this,&Widget::upDatePageOfLike);
    connect(ui->page_6,&rightForm::upDatePage,this,&Widget::upDatePageOfLike);

    connect(ui->slider, &sliderForm::progressChanged,this, &Widget::onFrameSetValueClicked);
    //播放
    connect(ui->start, &QPushButton::clicked,this, &Widget::onPlayClicked);
    connect(ui->pre, &QPushButton::clicked,this, &Widget::onPlayPreClicked);
    connect(ui->next, &QPushButton::clicked,this, &Widget::onPlayNextClicked);
    //音量调节和播放类型
    connect(ui->volume, &QPushButton::clicked, this, &Widget::onVolumeClicked);
    connect(ui->mode, &QPushButton::clicked, this, &Widget::onPlayTypeClicked);

    connect(ui->page_4, &rightForm::play, this, &Widget::onPlayAllClicked);
    connect(ui->page_5, &rightForm::play, this, &Widget::onPlayAllClicked);
    connect(ui->page_6, &rightForm::play, this, &Widget::onPlayAllClicked);

    //双击
    connect(ui->page_4, &rightForm::playMusicByIndex,this, &Widget::playPageByIndex);
    connect(ui->page_5, &rightForm::playMusicByIndex,this, &Widget::playPageByIndex);
    connect(ui->page_6, &rightForm::playMusicByIndex,this, &Widget::playPageByIndex);

    connect(ui->lrc, &QPushButton::clicked, this, &Widget::showLrcPage);

    connect(ui->page_4, &rightForm::musicFilesSelected, this, [this](listForm& musicList) {
        this->musiclist = musicList;
    });
    connect(ui->page_5, &rightForm::musicFilesSelected, this, [this](listForm& musicList) {
        this->musiclist = musicList;
    });
    connect(ui->page_6, &rightForm::musicFilesSelected, this, [this](listForm& musicList) {
        this->musiclist = musicList;
    });
}

bool Widget::initDB()
{
    //创建数据库驱动
    db = QSqlDatabase::addDatabase("QSQLITE");

    //设置名称
    db.setDatabaseName("resoundmusic.db");

    //打开数据库
    if (!db.open()) {
        QMessageBox::information(this, "无法打开数据库", db.lastError().text());
        return false;
    }

    //建表
    QSqlQuery query;
    query.exec(R"(
        CREATE TABLE IF NOT EXISTS musiclist (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            itemid VARCHAR(50) UNIQUE,
            name VARCHAR(50),
            author VARCHAR(50),
            album VARCHAR(50),
            duration BIGINT,
            itemurl VARCHAR(250),
            isLike INTEGER,
            isHistory INTEGER
        )
    )");

    if (query.lastError().isValid()) {
        QMessageBox::information(this, "建表失败", query.lastError().text());
        return false;
    }
    return true;
}

void Widget::initData()
{
    musiclist.getMusicFormBD();
}

void Widget::mousePressEvent(QMouseEvent *event)
{
    if(event->button() == Qt::LeftButton)
    {
        // 获取ui->left在屏幕中的位置
        QPoint leftWidget = ui->left->mapToGlobal(QPoint(0, 0));
        QSize size = ui->left->size();
        QRect leftWidgetRect(leftWidget,size);
        // 判断鼠标是否点击在ui->left区域内
        if (leftWidgetRect.contains(event->globalPos())) {
            notMove = false;
            return;
        }
        //获取窗口相对坐标
        notMove = true;
        relpos = event->globalPos() - geometry().topLeft();
    }
    QWidget::mousePressEvent(event);
}

void Widget::mouseMoveEvent(QMouseEvent *event)
{
    if(event->buttons() == Qt::LeftButton && notMove)
    {
        move(event->globalPos() - relpos);
    }
}


void Widget::setupShadow()
{
    // 确保窗口背景透明
    setAttribute(Qt::WA_TranslucentBackground);
    // 创建阴影效果
    QGraphicsDropShadowEffect *shadow = new QGraphicsDropShadowEffect(this);
    shadow->setBlurRadius(10);
    shadow->setColor(QColor(0, 0, 0, 80));
    shadow->setOffset(0, 0);
    // 应用阴影
    this->setGraphicsEffect(shadow);

}

QJsonArray Widget::setRecImgAndText()
{
    //设置图片
    QVector<QString> imgname;
    imgname << "01.png" << "02.png" << "03.png" << "04.png" << "05.png"
            << "06.png" << "07.png" << "08.png" << "09.png" << "10.png"
            << "11.png" << "12.png" << "13.png" << "14.png" << "15.png"
            << "16.png" << "17.png" << "18.png" << "19.png" << "20.png"
            << "21.png" << "22.png" << "23.png" << "24.png";
    std::random_shuffle(imgname.begin(),imgname.end());
    // qDebug() <<imgname[0];
    //设置文本
    QJsonArray arr;
    for(int i = 0; i < imgname.size(); i++)
    {
        QJsonObject object;
        object.insert("path", imgname[i]);
        QString setext = QString("推荐-%1").arg(i + 1, 2, 10, QChar('0'));
        object.insert("text", setext);
        arr.append(object);
    }
    return arr;
}

void Widget::initPlay()
{
    player = new QMediaPlayer(this);
    playlist = new QMediaPlaylist(this);

    //设置播放默认
    playlist->setPlaybackMode(QMediaPlaylist::Loop);
    player->setPlaylist(playlist);
    player->setVolume(50);

    connect(player, &QMediaPlayer::durationChanged,this, &Widget::onDdurationChanged);
    connect(player, &QMediaPlayer::positionChanged,this, &Widget::onPositionChanged);
    //状态改变
    connect(player, &QMediaPlayer::stateChanged,this, &Widget::onStateChanged);
    //源数据改变
    connect(player, &QMediaPlayer::metaDataAvailableChanged,this, &Widget::onMetaDataAvailableChanged);
    //播放列表索引改变的信号
    connect(playlist, &QMediaPlaylist::currentIndexChanged,this, &Widget::curPlayChanged);
}

void Widget::initMusicList()
{
    musiclist.getMusicFormBD();
    //刷新我喜欢列表
    ui->page_4->setMusicListPage(Page::likePage);
    ui->page_4->showItemonPage(musiclist);

    //刷新历史播放列表
    ui->page_6->setMusicListPage(Page::historyPage);
    ui->page_6->showItemonPage(musiclist);

    //刷新本地音乐列表
    ui->page_5->setMusicListPage(Page::loadPage);
    ui->page_5->showItemonPage(musiclist);
}

void Widget::addSystemAction()
{
    //程序关闭时更新数据库
    //
    //将数据写入数据库
    musiclist.addMusicToDB();
    //断连
    db.close();

    this->close();

}

void Widget::rightPageChange(int pageIndex)
{
    //清除之前点击样式
    QList<leftForm *> children = this->findChildren<leftForm *>();
    for(auto child : children)
    {
        if(child->getpageIndex() != pageIndex)
        {
            child->clearStyle();
        }
    }
    ui->stackedWidget->setCurrentIndex(pageIndex);
    notMove = false;
}

void Widget::on_exit_clicked()
{
    //窗口隐藏(显示在底部菜单栏)
    this->hide();
    // close();
}

void Widget::onRbtnClicked()
{
    //程序关闭时更新数据库
    //
    //将数据写入数据库
    musiclist.addMusicToDB();
    //断连
    db.close();

    this->close();
    QApplication::quit();

}
void Widget::onMaxClicked()
{
    qDebug() << "禁止最大化";
}

void Widget::onMinClicked()
{
    this->showMinimized();
}


void Widget::on_volume_clicked()
{
    // volume = new volumeForm(this);
    //获取volume的坐标
    QPoint pos = ui->volume->mapToGlobal(QPoint(0,0));
    // qDebug() <<pos;
    QPoint relpos = pos - QPoint(volume->width() / 2 - 15, volume->height());
    volume->move(relpos);
    volume->show();
}

void Widget::upDatePageOfLike(bool isLike, QString itemid)
{
    auto it = musiclist.getMusicId(itemid);
    if(it != musiclist.end())
    {
        it->setisLikeitem(isLike);
    }
    ui->page_4->showItemonPage(musiclist);
    ui->page_5->showItemonPage(musiclist);
    ui->page_6->showItemonPage(musiclist);
}

void Widget::onDdurationChanged(qint64 duration)
{
    if(durationSet)
        return;
    auto itemid = curPage->getMusicId(curindex);
    auto it = musiclist.getMusicId(itemid);
    if (it != musiclist.end()) {
        duration = it->getDurationitem();
    }
    onduration = duration;
    ui->label_5->setText(QString("%1:%2").arg(duration/1000/60,2,10,QChar('0'))
                                            .arg(duration/1000%60,2,10,QChar('0')));

    durationSet = true;
}

void Widget::onPositionChanged(qint64 duration)
{
    qint64 adjDur = duration / 2;
    ui->label_2->setText(QString("%1:%2").arg(adjDur/1000/60,2,10,QChar('0')).arg(adjDur/1000%60,2,10,QChar('0')));
    ui->slider->setProgress(float(adjDur) / float(onduration));
    if(playlist->currentIndex() >= 0)
        lrc->showLrc(adjDur);
}

void Widget::onStateChanged()
{
    if(player->state() == QMediaPlayer::PlayingState)
    {
        ui->start->setStyleSheet("border-image:url(:/pic/start.png);");
    }
    else
    {
        ui->start->setStyleSheet("border-image:url(:/pic/stop.png);");
    }
}

void Widget::onFrameSetValueClicked(float num)
{
    qint64 pos = qint64((float)onduration * num);

    pos = pos > onduration ? onduration : pos;
    pos = pos < 0 ? 0 : pos;

    ui->label_2->setText(QString("%1:%2").arg(pos/1000/60,2,10,QChar('0')).arg(pos/1000%60,2,10,QChar('0')));
    //从播放器获取的时长是原本的2倍，简单处理结果
    //是ogg转到MP3的结果
    //使用ogg不能进行播放歌曲无授权
    pos = pos * 2;
    player->setPosition(pos);
}

//底栏信息
void Widget::onMetaDataAvailableChanged(bool available)
{
    auto itemid = curPage->getMusicId(curindex);
    auto it = musiclist.getMusicId(itemid);

    QString author = it->getAuthoritem();
    QString name = it->getNameitem();
    QString album = it->getAlbumitem();

    ui->label->setText(name);
    ui->label_10->setText(author);

    lrc->setTitle(name);
    lrc->setAuthor(author);
    lrc->setAlbum(album);

    // 如果元数据可用
    if (available) {
        QVariant pic = player->metaData("ThumbnailImage");
        if (pic.isValid())
        {
            QImage img = pic.value<QImage>();
            ui->pic->setPixmap(QPixmap::fromImage(img));
        }
        else
        {
            ui->pic->setPixmap(QPixmap::fromImage(QImage(":/pic/01.png")));
        }
        ui->pic->setScaledContents(true);
    }

    if(it != musiclist.end())
    {
        lrc->parseLrc(it->getLrcPath());
    }
}

void Widget::onPlayClicked()
{
    if(player->state() == QMediaPlayer::PlayingState)
    {
        player->pause();
    }
    else if(player->state() == QMediaPlayer::PausedState || player->state() == QMediaPlayer::StoppedState)
    {
        player->play();
    }
    else
    {}
}

void Widget::onPlayNextClicked()
{
    playlist->next();
}

void Widget::onPlayAllClicked(Page Page)
{
    rightForm* page;
    switch (Page)
    {
    case Page::loadPage:
        page = ui->page_5;
        break;
    case Page::likePage:
        page = ui->page_4;
        break;
    case Page::historyPage:
        page = ui->page_6;
    default:
        break;
    }

    playPageByIndex(page,0);
}

void Widget::onPlayPreClicked()
{
    playlist->previous();
}



void Widget::onVolumeClicked()
{
    QPoint pos = ui->volume->mapToGlobal(QPoint(0,0));
    QPoint point = QCursor::pos() - QPoint(volume->width()/2, volume->height());
    point.setX(pos.x()-40);
    volume->move(point);
    volume->show();
    connect(volume, &volumeForm::getStatus, this, [=](bool state){
        if (state)
        {
            ui->volume->setStyleSheet("border-image:url(:/pic/volume.png);}");
        }
        else
        {
            ui->volume->setStyleSheet("border-image:url(:/pic/volumeno.png);}");
        }
    });

    // 设置音量的信号和槽函数
    connect(volume,&volumeForm::setVolume,this,[=](int num){
                player->setVolume(num);
            });
}

void Widget::onPlayTypeClicked()
{
    // 调整播放模式
    if(playlist->playbackMode() == QMediaPlaylist::Loop)
    {
        // 列表循环
        ui->mode->setToolTip("随机播放");
        ui->mode->setStyleSheet("#mode{border-image:url(:/pic/srand.png);}");
        playlist->setPlaybackMode(QMediaPlaylist::Random);
    }
    else if(playlist->playbackMode() == QMediaPlaylist::Random)
    {
        // 随机播放
        ui->mode->setToolTip("单曲循环");
        ui->mode->setStyleSheet("#mode{border-image:url(:/pic/one.png);}");
        playlist->setPlaybackMode(QMediaPlaylist::CurrentItemInLoop);
    }
    else if(playlist->playbackMode()==QMediaPlaylist::CurrentItemInLoop)
    {
        // 单曲循环
        ui->mode->setToolTip("循环播放");
        ui->mode->setStyleSheet("#mode{border-image:url(:/pic/recycle.png);}");
        playlist->setPlaybackMode(QMediaPlaylist::Sequential);
    }
    else if(playlist->playbackMode()==QMediaPlaylist::Sequential)
    {
        ui->mode->setToolTip("顺序播放");
        ui->mode->setStyleSheet("#mode{border-image:url(:/pic/order.png);}");
        playlist->setPlaybackMode(QMediaPlaylist::Loop);
    }
    else
        qDebug() << "似乎到了新区域...";
}


void Widget::showLrcPage()
{
    lrcAnimetion = new QPropertyAnimation(lrc,"geometry",this);
    lrcAnimetion->setDuration(250);
    lrcAnimetion->setStartValue(QRect(12, lrc->height() + 12, lrc->width(), lrc->height()));
    lrcAnimetion->setEndValue(QRect(12, 12, lrc->width(), lrc->height()));
    lrc->show();
    lrcAnimetion->start();
}

void Widget::setMusicPage(rightForm* page)
{
    //更新页面id
    curPage = page;
}

void Widget::curPlayChanged(int index)
{
    //更新页面索引
    curindex = index;
    QString itemid = curPage->getMusicId(index);
    auto it = musiclist.getMusicId(itemid);
    if(it != musiclist.end())
    {
        it->setisHistoryitem(true);
    }
    ui->page_6->showItemonPage(musiclist);
    durationSet = false;
}

void Widget::playPageByIndex(rightForm* page, int index)
{
    this->setMusicPage(page);
    playlist->clear();
    page->addMusicToPlayList(musiclist, playlist);
    playlist->setCurrentIndex(index);
    player->play();
}

void Widget::upDateAnimation()
{
    //获取索引
    int index = ui->stackedWidget->indexOf(curPage);
    if(-1 == index)
    {
        qDebug() << "该页面不存在";
        return;
    }
    //获取QQMusci界面上所有的btForm
    QList<leftForm*> leftForms = this->findChildren<leftForm*>();
    for(auto leftForm :leftForms)
    {
        if(leftForm->getpageIndex() == index)
            leftForm->showAnimation(true);

        else
            leftForm->showAnimation(false);
    }
}


void Widget::on_skin_clicked()
{
    if(color)
        ui->widget->setStyleSheet("background-color:rgb(0, 0, 0);color:white;");
    else
        ui->widget->setStyleSheet("background-color:rgb(240, 240, 240);color:black;");
    color = !color;
    // qDebug() << "皮肤出差了...";
}



void Widget::on_setting_clicked()
{
    qDebug() << "积极维修中...";
}

